<template>
  <div class="invoice-result-container">
    <el-card class="result-card">
      <div class="result-content">
        <!-- 成功状态 -->
        <div v-if="isSuccess" class="success-result">
          <div class="result-icon success">
            <el-icon><Check /></el-icon>
          </div>
          <h2 class="result-title">发票开具成功！</h2>
          <p class="result-message">您的发票已成功开具，相关信息如下：</p>
          
          <div class="invoice-info">
            <div class="info-item">
              <label>发票号码：</label>
              <span class="invoice-number">{{ invoiceNumber }}</span>
            </div>
            <div class="info-item">
              <label>开票金额：</label>
              <span class="invoice-amount">¥{{ invoiceAmount }}</span>
            </div>
            <div class="info-item">
              <label>开票时间：</label>
              <span>{{ formatTime(new Date()) }}</span>
            </div>
          </div>

          <div class="result-actions">
            <el-button @click="viewInvoice" type="primary" size="large" :icon="View">
              查看发票详情
            </el-button>
            <el-button @click="downloadInvoice" type="success" size="large" :icon="Download">
              下载发票
            </el-button>
            <el-button @click="printInvoice" type="warning" size="large" :icon="Printer">
              打印发票
            </el-button>
            <el-button @click="createNewInvoice" size="large" :icon="Plus">
              继续开票
            </el-button>
          </div>
        </div>

        <!-- 失败状态 -->
        <div v-else class="error-result">
          <div class="result-icon error">
            <el-icon><Close /></el-icon>
          </div>
          <h2 class="result-title">发票开具失败</h2>
          <p class="result-message">很抱歉，发票开具过程中出现了问题：</p>
          
          <div class="error-info">
            <div class="error-item">
              <label>错误代码：</label>
              <span>{{ errorCode }}</span>
            </div>
            <div class="error-item">
              <label>错误信息：</label>
              <span>{{ errorMessage }}</span>
            </div>
            <div class="error-item">
              <label>失败时间：</label>
              <span>{{ formatTime(new Date()) }}</span>
            </div>
          </div>

          <div class="result-actions">
            <el-button @click="retryInvoice" type="primary" size="large" :icon="Refresh">
              重新开票
            </el-button>
            <el-button @click="contactSupport" type="warning" size="large" :icon="Service">
              联系客服
            </el-button>
            <el-button @click="goBackToList" size="large" :icon="ArrowLeft">
              返回列表
            </el-button>
          </div>
        </div>

        <!-- 操作提示 -->
        <div class="operation-tips">
          <h3>操作提示</h3>
          <ul>
            <li v-if="isSuccess">
              <el-icon><InfoFilled /></el-icon>
              发票已发送至收票方邮箱，请注意查收
            </li>
            <li v-if="isSuccess">
              <el-icon><InfoFilled /></el-icon>
              发票信息已同步至税务系统，可在发票查验平台查询
            </li>
            <li v-if="isSuccess">
              <el-icon><InfoFilled /></el-icon>
              建议保存发票副本以备后续使用
            </li>
            <li v-if="!isSuccess">
              <el-icon><Warning /></el-icon>
              如问题持续存在，请联系技术支持
            </li>
            <li v-if="!isSuccess">
              <el-icon><Warning /></el-icon>
              请检查网络连接和系统状态
            </li>
          </ul>
        </div>
      </div>
    </el-card>

    <!-- 发票详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="发票详情"
      width="80%"
      :before-close="handleDetailClose"
    >
      <div class="invoice-detail" v-if="invoiceDetail">
        <div class="detail-section">
          <h3>发票信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <label>发票号码：</label>
                <span>{{ invoiceDetail.invoiceNumber }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>发票类型：</label>
                <span>{{ getInvoiceTypeName(invoiceDetail.invoiceType) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>开票日期：</label>
                <span>{{ invoiceDetail.issueDate }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3>开票方信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label>开票方名称：</label>
                <span>{{ invoiceDetail.issuer.name }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label>纳税人识别号：</label>
                <span>{{ invoiceDetail.issuer.taxNumber }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3>收票方信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label>收票方名称：</label>
                <span>{{ invoiceDetail.recipient.name }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label>纳税人识别号：</label>
                <span>{{ invoiceDetail.recipient.taxNumber }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3>商品信息</h3>
          <el-table :data="invoiceDetail.goods" border>
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="specification" label="规格型号" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="quantity" label="数量" />
            <el-table-column prop="unitPrice" label="单价">
              <template #default="{ row }">
                ¥{{ row.unitPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额">
              <template #default="{ row }">
                ¥{{ (row.quantity * row.unitPrice).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h3>金额汇总</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <label>商品总金额：</label>
                <span>¥{{ calculateTotalAmount().toFixed(2) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>税额：</label>
                <span>¥{{ calculateTaxAmount().toFixed(2) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>价税合计：</label>
                <span class="total-amount">¥{{ calculateTotalWithTax().toFixed(2) }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button @click="downloadInvoice" type="primary">下载发票</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

// 接口定义
interface InvoiceDetail {
  invoiceNumber: string
  invoiceType: string
  issueDate: string
  issuer: {
    name: string
    taxNumber: string
  }
  recipient: {
    name: string
    taxNumber: string
  }
  goods: Array<{
    name: string
    specification: string
    unit: string
    quantity: number
    unitPrice: number
  }>
}

// 路由
const router = useRouter()
const route = useRoute()

// 响应式数据
const detailVisible = ref(false)
const invoiceDetail = ref<InvoiceDetail | null>(null)

// 计算属性
const isSuccess = computed(() => {
  return route.query.success === 'true'
})

const invoiceNumber = computed(() => {
  return route.query.invoiceNumber as string || 'INV20250101001'
})

const invoiceAmount = computed(() => {
  return route.query.amount as string || '0.00'
})

const errorCode = computed(() => {
  return route.query.errorCode as string || 'E001'
})

const errorMessage = computed(() => {
  return route.query.errorMessage as string || '系统繁忙，请稍后重试'
})

// 方法
const formatTime = (date: Date) => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getInvoiceTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    special: '增值税专用发票',
    normal: '增值税普通发票',
    electronic: '电子普通发票'
  }
  return typeMap[type] || '发票'
}

const viewInvoice = () => {
  // 模拟加载发票详情
  invoiceDetail.value = {
    invoiceNumber: invoiceNumber.value,
    invoiceType: 'normal',
    issueDate: new Date().toISOString().split('T')[0],
    issuer: {
      name: '示例开票方有限公司',
      taxNumber: '91110000MA0012345678'
    },
    recipient: {
      name: '示例收票方有限公司',
      taxNumber: '91110000MA8765432109'
    },
    goods: [
      {
        name: '示例商品',
        specification: '标准版',
        unit: '件',
        quantity: 1,
        unitPrice: parseFloat(invoiceAmount.value)
      }
    ]
  }
  detailVisible.value = true
}

const downloadInvoice = () => {
  ElMessage.success('发票下载功能开发中...')
  // 这里可以实现实际的下载逻辑
}

const printInvoice = () => {
  ElMessage.success('发票打印功能开发中...')
  // 这里可以实现实际的打印逻辑
}

const createNewInvoice = () => {
  router.push('/invoice/form')
}

const retryInvoice = () => {
  router.push('/invoice/confirm')
}

const contactSupport = () => {
  ElMessage.info('客服联系方式：400-123-4567')
}

const goBackToList = () => {
  router.push('/invoice/list')
}

const handleDetailClose = () => {
  detailVisible.value = false
  invoiceDetail.value = null
}

const calculateTotalAmount = () => {
  if (!invoiceDetail.value) return 0
  return invoiceDetail.value.goods.reduce((total, item) => {
    return total + (item.quantity * item.unitPrice)
  }, 0)
}

const calculateTaxAmount = () => {
  return calculateTotalAmount() * 0.13
}

const calculateTotalWithTax = () => {
  return calculateTotalAmount() + calculateTaxAmount()
}

// 生命周期
onMounted(() => {
  // 页面加载完成后的初始化操作
  if (isSuccess.value) {
    ElMessage.success('发票开具成功！')
  } else {
    ElMessage.error('发票开具失败')
  }
})
</script>

<style scoped>
.invoice-result-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-card {
  max-width: 800px;
  width: 100%;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.result-content {
  padding: 40px;
  text-align: center;
}

.result-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  font-size: 40px;
}

.result-icon.success {
  background: #f0f9ff;
  color: #67c23a;
  border: 3px solid #67c23a;
}

.result-icon.error {
  background: #fef0f0;
  color: #f56c6c;
  border: 3px solid #f56c6c;
}

.result-title {
  margin: 0 0 15px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.result-message {
  margin: 0 0 30px 0;
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
}

.invoice-info,
.error-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  border: 1px solid #e4e7ed;
}

.info-item,
.error-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
}

.info-item:last-child,
.error-item:last-child {
  border-bottom: none;
}

.info-item label,
.error-item label {
  font-weight: 600;
  color: #606266;
}

.invoice-number {
  font-weight: 600;
  color: #409eff;
  font-size: 18px;
}

.invoice-amount {
  font-weight: 600;
  color: #e6a23c;
  font-size: 18px;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 40px;
  flex-wrap: wrap;
}

.operation-tips {
  background: #f0f9ff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #b3d8ff;
  text-align: left;
}

.operation-tips h3 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.operation-tips ul {
  margin: 0;
  padding-left: 20px;
}

.operation-tips li {
  margin: 8px 0;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 8px;
}

.invoice-detail {
  padding: 20px 0;
}

.detail-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.detail-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: 600;
  color: #606266;
  min-width: 120px;
  margin-right: 10px;
}

.detail-item span {
  color: #303133;
}

.total-amount {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .invoice-result-container {
    padding: 10px;
  }
  
  .result-content {
    padding: 20px;
  }
  
  .result-title {
    font-size: 24px;
  }
  
  .result-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .result-actions .el-button {
    width: 200px;
  }
  
  .info-item,
  .error-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item label,
  .error-item label {
    margin-bottom: 5px;
  }
}

@media (max-width: 480px) {
  .result-content {
    padding: 15px;
  }
  
  .result-icon {
    width: 60px;
    height: 60px;
    font-size: 30px;
  }
  
  .result-title {
    font-size: 20px;
  }
  
  .result-actions .el-button {
    width: 100%;
  }
}
</style>
